package com.solidsnake.scala.service

import com.solidsnake.scala.http.{HttpUtils, HttpHandlerField}
import java.nio.charset.Charset
import java.awt.image.BufferedImage
import com.solidsnake.scala.image.CalculateImageDataManager
import java.io.{File, FileOutputStream}

/**
 * Created with IntelliJ IDEA.
 * User: solidsnake
 * Date: 13-11-26
 * Time: 上午8:58
 * To change this template use File | Settings | File Templates.
 */
object ValidateCodeService {

  /**
   * 请求登录验证码
   * @param url
   * @param code
   * @param cookie
   * @return
   */
  def requestLoginValidateCode(url : String, code : String, cookie : String) = {
    val requestHandler = Map(HttpHandlerField.REFERER -> "http://app02.szaic.gov.cn/WERMIS2.WebUI/Default.aspx",
      HttpHandlerField.COOKIE -> cookie)
    HttpUtils.getImage(url, Map("code" -> code), Charset.forName("UTF-8"), requestHandler, true)
  }

  def requestQueryValidateCode(url : String, cookie : String) = {
    val requestHandler = Map(HttpHandlerField.REFERER -> "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/Name/SSDJEnterPage.aspx",
      HttpHandlerField.COOKIE -> cookie)
    HttpUtils.getImage(url, Map(), Charset.forName("UTF-8"), requestHandler, true)
  }

  /**
   *  获得登录验证码URL
   * @param htmlContent
   * @return (url， param)
   */
  def getLoginValidateUrl(htmlContent : String) = {
    val p = "<img[^>]*src=\"([a-zA-z]+://[^\"]*)\"[^>]*id=\"Login1_iCheckCode\"[^>]*>".r
    val p(validateUrl) = p.findFirstIn(htmlContent).getOrElse("")
    val loginValidateUrl = validateUrl.split("code=")(0).replace("?", "")
    val loginValidateParams = validateUrl.split("code=")(1)
    (loginValidateUrl, loginValidateParams)
  }

  def getQueryValidateUrl(htmlContent : String) = {
    val p = "<img[^>]*id=\"SSDJNCREnterPage1_iCheckCode\"[^>]*src=\"([^\"]*)\"[^>]*>".r
    val p(validateUrl) = p.findFirstIn(htmlContent).getOrElse("")

    validateUrl.replace("../", "http://app02.szaic.gov.cn/WERMIS2.WebUI/WebPages/") // 如果是相对路径转为绝对路径
  }

  /**
   * 计算验证码
   * @param image
   * @return
   */
  def calculateValidateCodeDate(image : Array[Byte]) : String = {
    def getTempFileByOs = {
      val props =System.getProperties(); //获得系统属性集
      props.getProperty("os.name") match {
        case "Linux" => "/home/solidsnake/桌面/abc/sb.gif"
        case _ => "D:\\sb.gif"
      }
    }
    new FileOutputStream(new File(getTempFileByOs)).write(image)
    val vcCodes = CalculateImageDataManager.readVerificationCode(getTempFileByOs)
    var vc = ""
    for(index <- 0 to 4) {
      vc += vcCodes(index)
    }
    println(vc)
    return vc
  }


}
